package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApArticle;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.feign.ApArticleController;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApUnlikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP不喜欢行为表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-18
 */
@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior> implements IApUnlikesBehaviorService {

    @Autowired
    IApBehaviorEntryService entryService;

    @Autowired
    private ApArticleController apArticleFeign;

    //保存不喜欢行为
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {

        //1 判断是否为空
        if (dto == null) {

            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2 获取当前用户信息
        User user = AppThreadLocalUtil.get();
        // 创建不喜欢行为对象
        ApUnlikesBehavior apLikesBehavior = new ApUnlikesBehavior();
        //3 用户已经登录情况下，保存数据
        if (user != null) {

            Integer userId = user.getUserId();
            //3.1 查询行为实体
            LambdaQueryWrapper<ApBehaviorEntry> query = new LambdaQueryWrapper<>();

            query.eq(ApBehaviorEntry::getEntryId,userId.toString());

            query.eq(ApBehaviorEntry::getType,1);

            ApBehaviorEntry one = entryService.getOne(query);
            //3.2 给不喜欢行为的实体id设置值
            apLikesBehavior.setEntryId(one.getId());
        }else {

            LambdaQueryWrapper<ApBehaviorEntry> query = new LambdaQueryWrapper<>();

            query.eq(ApBehaviorEntry::getEntryId,dto.getEquipmentId());

            query.eq(ApBehaviorEntry::getType,0);

            ApBehaviorEntry one = entryService.getOne(query);
            //3.3 给不喜欢行为的实体id设置值
            apLikesBehavior.setEntryId(one.getId());
        }

        //给不喜欢行为设置属性值
        apLikesBehavior.setCreatedTime(new Date());

        apLikesBehavior.setType(dto.getType());

        apLikesBehavior.setArticleId(dto.getArticleId());

        //4 保存操作
        this.save(apLikesBehavior);

        return ResponseResult.okResult(apLikesBehavior.getId());
    }
}
